<?php
/**
 * 参    数：
 * 作    者：szr
 * 功    能：积分管理记录
 * 修改日期：2021-4-14
 */

namespace Frieza\Modules\CreditManage\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmPointsManage;
use Doraemon\model\Member;
use Doraemon\tools\Curl;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Hhzbeads\Point\PointClient;
use Illuminate\Http\Request;
use Doraemon\pockets\config\IniConfig;
use Illuminate\Support\MessageBag;



//积分记录
class CreditController extends Controller
{

    private static $_config;

    const SENDCUIDS = '/home/adm_rsync_dir/SendUids.txt';

    private static function initConfig()
    {
        if (self::$_config == null) {
            self::$_config = IniConfig::getConfigSelect(PointClient::_CONFIG_FILE_, PointClient::_CONFIG_URL);
        }
    }

    //入口
    public function index(Request $request, Content $content)
    {

        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 20);

        $search = $request->all();
        //关键字
        $keyword = $search['use'];
        //uid||nickname
        $use = ($search['use_group'] == 0) ? 'uid' : 'nick';

        //奖励||扣除
        $type = $search['type'];

        if ($use == 'uid') {
            $nick = Member::getNickByUid($keyword);
            $uid = $keyword;
        }

        if ($use == 'nick') {
            $uid = Member::getUidByNick($keyword);
            $nick = $keyword;
        }

        $start = $search['time']['start'] ? $search['time']['start'] : date('Y-m-d', strtotime('-1day'));
        $startTime = strtotime($search['time']['start']) ? strtotime($search['time']['start']) : strtotime('-1day');
        $end = $search['time']['end'] ? $search['time']['end'] : date('Y-m-d', time());
        $endTime = strtotime($search['time']['end']) ? strtotime($search['time']['end']) + 86399 : time();

        //获取request_id
        $requestIds = AdmPointsManage::getRequestIds($startTime, $endTime, $uid, $type);


        $detail = array();
        if (!empty($requestIds)) {
            $requestId = implode(',', $requestIds);

            self::initConfig();
            $url = self::$_config['domain'] . '/search/list?uid=' . $uid . '&request_id=' . $requestId;
            $res = Curl::Request('GET', $url);
            $rs = [];
            if (isset($res['json']['data'])) {
                $rs = $res['json']['data'];
            }

            $detailBase = $rs ? $rs['point_list'] : [];
            $admManages = AdmPointsManage::getAllByUid($uid);
            $nick = Member::getNickByUid($uid);
            $manages = array();
            foreach ($admManages as $admManage) {
                $admManage['request_id'] = md5(md5($admManage['request_id']));
                $manages[] = $admManage;
            }

            foreach ($detailBase as $value) {
                foreach ($manages as $manage) {
                    if ($value["request_id"] == $manage['request_id']) {
                        $value['nick'] = $nick;
                        $value['addTime'] = date('Y-m-d H:i:s', $value['addtime']);
                        $value['adminId'] = $manage['adminId'];
                        $value['adminName'] = Admin::user()->find($manage['admin_id'])->name;
                        $detail[] = $value;
                    }
                }
            }
        }


        $gridModel = new pGridDataModel($detail, $page, $pageSize);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();
            $grid->disableColumnSelector();

            $grid->filter(function ($filter) {
                $filter->disableIdFilter();

                $filter->column(8, function ($filter) {
                    $filter->group('use', '用户', function ($group) {
                        $group->equal('uid');
                        $group->equal('nick');
                    });
                });

                $filter->column(8, function ($filter) {
                    $filter->equal('type', '类型')->radio([
                        'adm-award' => '运营奖励',
                        'adm-deduct' => '运营扣除'
                    ])->default('adm-award');
                });

                $filter->column(12, function ($filter) {
                    $filter->between("time", "时间范围")->datetime();
                });
                $filter->expand();
            });

            $grid->column('adminName', '操作人');
            $grid->column('addTime', '操作时间');
            $grid->column('event_name', '操作')->display(function ($event_name){
                if ($event_name == 'adm-award'){
                    return '运营奖励';
                }elseif ($event_name == 'adm-deduct') {
                    return '运营扣除';
                }else{
                    return ' ';
                }
            });
            $grid->column('nick', '用户');
            $grid->column('hope_point', '分数');
        });

        $tab = new Tab();
        $tab->add('积分修改记录', $listGrid->render(), true);
        $tab->addLink('下发积分', 'sendCredit');
        $tab->addLink('用户积分明细', 'getPointList');
        $content->row($tab);
        return $content
            ->header('积分修改记录')
            ->breadcrumb(['text' => '积分修改记录']);
    }

    public function sendCredit(Request $request, Content $content)
    {
        $tab = new Tab();
        $form = new Form();

        $form->textarea('uids', '用户id')->required()->help('一行一个');
        $form->text('point', '积分数')->required()->help('仅支持正整数');
        $form->radio('eventName', '类型')
            ->options([PointConfig::POINT_TYPE_ADM_AWARD => '运营奖励',
                PointConfig::POINT_TYPE_ADM_DEDUCT => '运营扣除'])->default(PointConfig::POINT_TYPE_ADM_AWARD);
        $form->text('ext_infos', '备注');
        $form->radio('is_send', '是否推送消息')
            ->options([
                0 => '否',
                1 => '是'
            ])->default(0)
            ->when(1, function (Form $form) {
                $form->text('title', '标题');
                $form->textarea('content', '正文');
                $form->imgUpload('img', '上传图片');
                $form->text('link', '跳转链接');
            });
        $form->action(url('admin/CreditManage/save'));
        $tab->addLink('积分修改记录', 'index');
        $tab->add('下发积分', $form->render(), true);
        $tab->addLink('用户积分明细', 'getPointList');

        return $content
            ->header('下发积分')
            ->breadcrumb(['text' => '下发积分'])
            ->row($tab);
    }

    public function save(Request $request)
    {
        $params = $request->all();

        $uids = explode("\r\n", $params['uids']);
        $t = array();
        //去空格
        foreach ($uids as $uid) {
            $t[] = trim($uid);
        }
        $uids = $t;


        $point = $params['point'];
        $eventName = $params['eventName'];
        $extInfos = $params['extInfos'];

        //下发积分
        $source = 'admin';
        foreach ($uids as $uid) {
            $requestId = $source . $eventName . $uid . date('YmdHis');
            $msg['detail'] = $extInfos;

            $res = true;
            switch ($eventName) {
                case PointConfig::POINT_TYPE_ADM_AWARD:
                    $res = PointClient::awardPoint($uid, $point, $eventName, $requestId, $source, $extInfos);
                    break;

                case PointConfig::POINT_TYPE_ADM_DEDUCT:
                    $res = PointClient::deductPoint($uid, $point, $eventName, $requestId, $source, $extInfos);
                    break;
            }

            if (!$res) {
                throw new \Exception('下发积分失败');
            }

            //存表
            $adminId = Admin::user()->id;
            AdmPointsManage::addOne($adminId, $requestId, $uid, $eventName);

//                //下发消息
//                if ($is_send == '1') {
//                    $title = $params['title'];
//                    $content = $params['content'];
//                    $link = $params['link'];
//                    $pic = $params['img'];
//                    $data['uid'] = $uid;
//                    $data['admin_id'] = $admin_id;
//                    $data['message'] = $title;
//                    $data['handle_message'] = $content;
//                    $data['link'] = $link;
//                    $data['addtime'] = time();
//                    $data['status'] = 0;
//                    $data['img_pic_url'] = $pic;
//                    $data['title'] = $title;
//                    $data_id = mBatchSend::insert($data);
//                    sBatchSend::sendMsg($uid, $data, $data_id);
//                }
        }
        $success = new MessageBag(['title' => '操作成功']);
        return back()->with(compact('success'));
    }


    public function getPointList(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 20);
        $params = $request->all();
        $data = array();

        //搜索条件
        $start = $params['time']['start'] ? $params['time']['start'] : date('Y-m-d', strtotime('-1day'));
        $startTime = strtotime($params['time']['start']) ? strtotime($params['time']['start']) : strtotime('-1day');
        $end = $params['time']['end'] ? $params['time']['end'] : date('Y-m-d', time());
        $endTime = strtotime($params['time']['end']) ? strtotime($params['time']['end']) + 86399 : time();

        self::initConfig();
        if ($params['search'] == 'get') {
            $url = self::$_config['domain'] . '/search/list?uid=' . $params['uid'] . '&type=' . '1';
        } elseif ($params['search'] == 'put') {
            $url = self::$_config['domain'] . '/search/list?uid=' . $params['uid'] . '&type=' . '2';
        } else {
            $url = self::$_config['domain'] . '/search/list?uid=' . $params['uid'];
        }

        $res = Curl::Request('GET', $url);
        $rs = [];
        if (isset($res['json']['data'])) {
            $rs = $res['json']['data'];
        }
        $detail = $rs ? $rs['point_list'] : [];

        if (isset($params['time']['start']) && isset($params['time']['end'])) {
            foreach ($detail as $value) {
                $value['type'] = ($value['type'] == 1) ? '获取' : '扣除';
                $value['nickname'] = Member::getNickByUid($params['uid']);
                $value['addTime'] = date('Y-m-d H:i:s', $value['addtime']);
                $data[] = $value;
            }
        }
        foreach ($detail as $value) {
            if ($startTime <= $value['addtime'] && $endTime >= $value['addtime']) {
                $value['type'] = ($value['type'] == 1) ? '获取' : '扣除';
                $value['nickname'] = Member::getNickByUid($params['uid']);
                $value['addTime'] = date('Y-m-d H:i:s', $value['addtime']);
                $data[] = $value;
            }

        }
        $gridModel = new pGridDataModel($data, $page, $pageSize);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();
            $grid->disableColumnSelector();

            $grid->filter(function ($filter) {
                $filter->disableIdFilter();

                $filter->column(8, function ($filter) {
                    $filter->equal('uid', '用户id');
                    $filter->equal('search', '操作')->radio([
                        'get' => '获取',
                        'put' => '扣除',
                        '' => '全部'
                    ])->default(0);
                });

                $filter->column(12, function ($filter) {
                    $filter->between('time', '时间')->datetime();
                });

                $filter->expand();
            });

            $grid->column('uid', '用户id');
            $grid->column('addTime', '操作时间');
            $grid->column('nickname', '用户昵称');
            $grid->column('type', '操作');
            $grid->column('hope_point', '分数');
            $grid->column('event_name', '详情')->using(PointConfig::POINT_EVENT_NAME_MAP);


        });

        $tab = new Tab();
        $tab->addLink('积分修改记录', 'index');
        $tab->addLink('下发积分', 'sendCredit');
        $tab->add('用户积分明细', $listGrid->render(), true);
        $content->row($tab);
        return $content
            ->header('用户积分明细')
            ->breadcrumb(['text' => '用户积分明细']);

    }
}
